package com.rover.system.controller;

import com.grid.DataGrid;
import com.grid.Page;

import com.rover.system.entity.Code;
import com.rover.system.entity.CodeValue;
import com.rover.system.service.CodeService;
import com.rover.system.service.CodeValueService;
import com.utils.HqlGenerateUtil;
import com.utils.JSEscape;
import com.utils.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户
 */
@Controller
@RequestMapping("/codeValueController")
public class CodeValueController {

    @Autowired
    private CodeValueService codeValueService;

    @Autowired
    private CodeService codeService;
    // 用户管理
    @RequestMapping("/query")
    @ResponseBody
    public Map<String, Object> query(HttpServletRequest request, Page page,
                                     HttpServletResponse response) throws Exception {

        Map<String, Object> map = new HashMap<String, Object>();
        try {
            HqlGenerateUtil.installHql(request, Code.class, page);
            DataGrid dataGrid = codeValueService.query(page);
            map = JsonUtil.JSONString(dataGrid.getResult(),
                    dataGrid.getTotalCount());
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;


    }

    // 用户管理
    @RequestMapping("/queryTree")
    @ResponseBody
    public Map<String, Object> queryTree(HttpServletRequest request, Page page,
                                         HttpServletResponse response) throws Exception {
        HqlGenerateUtil.installHql(request, Code.class, page);
        Map<String, Object> map = new HashMap<String, Object>();
        DataGrid dataGrid = codeValueService.query(page);
        map = JsonUtil.JSONString(dataGrid.getResult(),
                dataGrid.getTotalCount());
        return map;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> save(CodeValue codeValue, HttpServletRequest request)
            throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Boolean success = true;
        String message = "";
        try {
            String codeId = request.getParameter("codeId");
            if (codeValueService.isItemTextRepeat(codeValue, Integer.valueOf(codeId))) {
                success = false;
                message = "此编码名称已存在，请重新输入！";
            } else if (codeValueService.isItemValueRepeat(codeValue, Integer.valueOf(codeId))) {
                success = false;
                message = "此编码值已存在，请重新输入！";
            } else
                codeValueService.save(codeValue, codeId);
            map.put("success", success);
            map.put("message", message);
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public
    @ResponseBody
    Map<String, Object> delete(@RequestParam("id") String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        // String id = request.getParameter("id");
        try {
            codeValueService.delete(Integer.valueOf(id));
            map.put("success", true);
            map.put("message", "");

        } catch (Exception e) {
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/treeSave", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> treeSave(CodeValue codeValue, HttpServletRequest request)
            throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Boolean success = true;
        String message = "";
        try {
            String codeId = request.getParameter("codeId");

            if (codeValueService.isItemTextRepeat(codeValue, Integer.valueOf(codeId))) {
                success = false;
                message = "此编码名称已存在，请重新输入！";
            } else if (codeValueService.isItemValueRepeat(codeValue, Integer.valueOf(codeId))) {
                success = false;
                message = "此编码值已存在，请重新输入！";
            } else {
                if (codeValue.getId() == null)
                    codeValueService.treeSave(codeValue, Integer.valueOf(codeId));
                else {
                    codeValueService.treeUpdate(codeValue, Integer.valueOf(codeId));
                }
            }

            map.put("success", success);
            map.put("message", message);
        } catch (Exception e) {
            // logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    /*
    *根据编码名称获取对于的列表值
     */
    @RequestMapping(value = "/getCodeValue")
    @ResponseBody
    public  Map<String, Object> getCodeValue(HttpServletRequest request,
                                     HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map.put("success", true);
            map.put("rows",Code.allCodeValue.get(JSEscape.unEscape(request.getParameter("codeName"))) );
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

   //根据字典名称，和编码值获取值
    @RequestMapping(value = "/getItemValue")
    @ResponseBody
    public    Map<String, Object> getValue(HttpServletRequest request,
                                     HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map.put("success", true);
            List<CodeValue> list=   Code.allCodeValue.get(JSEscape.unEscape(request.getParameter("codeName")));
            CodeValue codeValue;
           for(int i=0;i<list.size();i++){
               codeValue=  list.get(i);
               if(codeValue.getItemValue().equals(JSEscape.unEscape(request.getParameter("itemValue")))) {
                   map.put("data", codeValue.getItemText());
                   break;
               }
           }
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    /*
     * 根据codeId获取treeCode的json数据
     * @idType  id的值是itenValue还是treeCode
     * */
    @RequestMapping("/treeJsonId")
    @ResponseBody
    public void treeJsonId(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Integer codeId=null;
        if(StringUtils.isNotBlank(request.getParameter("spareProperty")))     {
            codeId=codeService.getCodeIdSpareProperty(request.getParameter("spareProperty")) ;
        }
        else
        {
            codeId=  Integer.valueOf(request.getParameter("codeId"))  ;
        }
        List<CodeValue> li = codeValueService.getTreeList(codeId);
        String str = json(li, request.getParameter("idType"));
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(str);
    }

    /*
     * 获取treeCode的json数据
     * @idType  id的值是itenValue还是treeCode
     * */
    @RequestMapping("/treeJsonName")
    @ResponseBody
    public void treeJsonName(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<CodeValue> li = codeValueService.getTreeList(request.getParameter("codeName"));

        String str = json(li, request.getParameter("idType"));
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(str);
    }

    private String json(List<?> li, String idType) {
        StringBuilder db = new StringBuilder();
        db.append("[");
        for (int i = 0; i < li.size(); i++) {
            CodeValue codeValue = (CodeValue) li.get(i);
            String strTemp = "";
            if (codeValue.getCodeValues().size() > 0) {
                strTemp = " ,\"leaf\": \"false\" ,\"children\": " + json(Arrays.asList(codeValue.getCodeValues().toArray()), idType);
            } else {
                strTemp = " ,\"leaf\": \"true\" ";
            }
            String id = "";
            if (idType.equals("itenValue")) {
                id = codeValue.getItemValue();
            } else
                id = codeValue.getTreeCode();
            if ((li.size() - 1) == i) {
                db.append("{\"text\": \"" + codeValue.getItemText() + "\",\"id\":\"" + id + "\",\"treeCode\":\"" + codeValue.getTreeCode() + "\"" + strTemp + "}");
            } else {
                db.append("{\"text\": \"" + codeValue.getItemText() + "\",\"id\":\"" + id + "\",\"treeCode\":\"" + codeValue.getTreeCode() + "\"" + strTemp + "},");
            }
        }
        db.append(" ]");
        return db.toString();
    }


}
